# -*- coding: utf-8 -*-
from flask import Flask, request, jsonify
from alibabacloud_green20220302.client import Client
from alibabacloud_green20220302 import models
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.client import Client as UtilClient
from alibabacloud_tea_util import models as util_models
from flask_cors import CORS
import json
import uuid
import oss2
import base64
from io import BytesIO
from PIL import Image
import time
import os

app = Flask(__name__)
CORS(app)  # 启用CORS支持

# 全局变量
is_vpc = False
token_dict = dict()
bucket = None

def create_client():
    """
    初始化内容安全客户端
    """
    config = Config(
        access_key_id='LTAI5tE8nZL7b1MY1gA18gEX',
        access_key_secret='sgFOXlzBZUneuphTFVDAYM5qzmo7KV',
        connect_timeout=3000,
        read_timeout=6000,
        region_id='cn-shanghai',
        endpoint='green-cip.cn-shanghai.aliyuncs.com'
    )
    return Client(config)

# 创建文件上传客户端
def create_oss_bucket(is_vpc, upload_token):
    global token_dict
    global bucket
    auth = oss2.StsAuth(
        upload_token.access_key_id, 
        upload_token.access_key_secret, 
        upload_token.security_token
    )

    end_point = upload_token.oss_internet_end_point if not is_vpc else upload_token.oss_internal_end_point
    bucket = oss2.Bucket(auth, end_point, upload_token.bucket_name)

# 上传文件到OSS
def upload_file_to_oss(file_data, upload_token):
    create_oss_bucket(is_vpc, upload_token)
    # 根据文件类型生成不同的扩展名
    file_extension = '.mp4'  # 默认为mp4
    object_name = upload_token.file_name_prefix + str(uuid.uuid1()) + file_extension
    bucket.put_object(object_name, file_data)
    return object_name

@app.route('/api/analyze-text', methods=['POST'])
def analyze_text():
    try:
        content = request.json.get('content')
        service_type = request.json.get('serviceType', 'comment_detection')
        print("\n=== 请求信息 ===")
        print(f"检测类型: {service_type}")
        print(f"检测内容: {content}")
        
        if not content:
            return jsonify({'error': '文本内容不能为空'}), 400

        # 构建请求参数
        service_parameters = {
            'content': content,
            'dataId': str(uuid.uuid1())
        }

        # 根据不同的检测类型添加特定参数
        if service_type == 'nickname_detection':
            # 昵称检测需要使用nickname字段
            service_parameters = {
                'nickname': content,
                'dataId': str(uuid.uuid1())
            }
        elif service_type == 'ad_compliance_detection':
            # 广告合规检测需要添加行业类型
            service_parameters['context'] = {
                'industryType': 'default'
            }
        elif service_type == 'ai_art_detection':
            # AI生成内容检测可能需要特殊处理
            service_parameters['detectType'] = 'detect_ai_generated'

        print("\n=== 请求参数 ===")
        print(f"Service Parameters: {json.dumps(service_parameters, ensure_ascii=False, indent=2)}")

        # 创建运行时配置
        runtime = util_models.RuntimeOptions(
            read_timeout=10000,
            connect_timeout=10000
        )

        client = create_client()

        try:
            # 构建请求
            text_moderation_request = models.TextModerationRequest(
                service=service_type,
                service_parameters=json.dumps(service_parameters)
            )

            # 发送请求
            response = client.text_moderation_with_options(text_moderation_request, runtime)
            result = response.body.to_map()
            
            print("\n=== API 原始响应 ===")
            print(json.dumps(result, ensure_ascii=False, indent=2))

            # 检查响应状态
            if not response or not response.body:
                return jsonify({'error': '无效的API响应'}), 500

            # 直接返回API的原始响应
            return jsonify({
                'code': result.get('Code'),
                'data': result.get('Data'),
                'message': result.get('Message'),
                'requestId': result.get('RequestId')
            })

        except Exception as api_error:
            print(f'\n=== API 错误 ===\n{str(api_error)}')
            # 尝试北京区域
            try:
                config = Config(
                    access_key_id='LTAI5tE8nZL7b1MY1gA18gEX',
                    access_key_secret='sgFOXlzBZUneuphTFVDAYM5qzmo7KV',
                    region_id='cn-beijing',
                    endpoint='green-cip.cn-beijing.aliyuncs.com'
                )
                client = Client(config)
                response = client.text_moderation_with_options(text_moderation_request, runtime)
                result = response.body.to_map()
                
                return jsonify({
                    'code': result.get('Code'),
                    'data': result.get('Data'),
                    'message': result.get('Message'),
                    'requestId': result.get('RequestId')
                })
            except Exception as beijing_error:
                print('Beijing API Error:', str(beijing_error))
                return jsonify({'error': f'API调用错误: {str(beijing_error)}'}), 500

    except Exception as e:
        print(f'\n=== 一般错误 ===\n{str(e)}')
        return jsonify({'error': str(e)}), 500
    
@app.route('/api/analyze-audio', methods=['POST'])
def analyze_audio():
    try:
        if 'audio' not in request.files:
            return jsonify({'error': '未找到音频文件'}), 400
            
        audio_file = request.files['audio']
        service_type = request.form.get('serviceType', 'audio_media_detection')

        try:
            # 创建客户端
            client = create_client()
            
            # 获取上传凭证
            token_response = client.describe_upload_token()
            upload_token = token_response.body.data

            # 直接读取文件内容到内存
            file_content = audio_file.read()

            # 上传文件到OSS（内存直传）
            auth = oss2.StsAuth(
                upload_token.access_key_id,
                upload_token.access_key_secret,
                upload_token.security_token
            )
            bucket = oss2.Bucket(
                auth,
                upload_token.oss_internet_end_point,
                upload_token.bucket_name
            )
            object_name = f"{upload_token.file_name_prefix}{uuid.uuid4()}{os.path.splitext(audio_file.filename)[1]}"
            bucket.put_object(object_name, file_content)

            # 提交检测任务
            service_parameters = {
                "ossBucketName": upload_token.bucket_name,
                "ossObjectName": object_name,
                "dataId": str(uuid.uuid4())
            }
            moderation_request = models.VoiceModerationRequest(
                service=service_type,
                service_parameters=json.dumps(service_parameters)
            )
            
            # 获取任务ID
            submit_response = client.voice_moderation_with_options(moderation_request, util_models.RuntimeOptions())
            task_id = submit_response.body.data.task_id

            # 轮询获取结果（最多30次，每次间隔2秒）
            for i in range(30):
                time.sleep(2)
                result_request = models.VoiceModerationResultRequest(
                    service=service_type,
                    service_parameters=json.dumps({'taskId': task_id})
                )
                result_response = client.voice_moderation_result(result_request)
                
                if result_response.body.code == 200:
                    result_data = result_response.body.data.to_map()
                    print("解析后的响应数据:", json.dumps(result_data, indent=2, ensure_ascii=False))
                    
                    # 修改判断条件：当存在RiskLevel和SliceDetails时返回结果
                    if result_data.get('RiskLevel') and result_data.get('SliceDetails'):
                        return jsonify({
                            'code': 200,
                            'data': result_data
                        })

            return jsonify({'error': '检测超时'}), 500

        except Exception as e:
            print("发生异常:", str(e))
            import traceback
            print(traceback.format_exc())
            return jsonify({'error': str(e)}), 500

    except Exception as e:
        print("外层异常:", str(e))
        return jsonify({'error': str(e)}), 500

@app.route('/api/analyze-image', methods=['POST'])
def analyze_image():
    try:
        if 'image' not in request.files:
            return jsonify({'error': '未找到图片文件'}), 400
            
        image_file = request.files['image']
        service_type = request.form.get('serviceType', 'baselineCheck')
        
        print("\n=== 请求信息 ===")
        print(f"检测类型: {service_type}")
        print(f"文件名: {image_file.filename}")

        # 读取图片数据
        image_data = image_file.read()
        
        # 创建客户端
        client = create_client()
        runtime = util_models.RuntimeOptions(
            read_timeout=10000,
            connect_timeout=10000
        )

        # 获取上传token
        upload_token = token_dict.get('cn-shanghai')
        if not upload_token or int(upload_token.expiration) <= int(time.time()):
            response = client.describe_upload_token()
            upload_token = response.body.data
            token_dict['cn-shanghai'] = upload_token

        # 上传文件到OSS
        object_name = upload_file_to_oss(image_data, upload_token)

        # 构建检测参数
        service_parameters = {
            'ossBucketName': upload_token.bucket_name,
            'ossObjectName': object_name,
            'dataId': str(uuid.uuid1())
        }

        # 创建图片检测请求
        image_moderation_request = models.ImageModerationRequest(
            service=service_type,
            service_parameters=json.dumps(service_parameters)
        )

        try:
            # 发送请求
            response = client.image_moderation_with_options(image_moderation_request, runtime)
            result = response.body.to_map()
            
            print("\n=== API 原始响应 ===")
            print(json.dumps(result, ensure_ascii=False, indent=2))

            if not response or not response.body:
                return jsonify({'error': '无效的API响应'}), 500

            return jsonify({
                'code': result.get('Code'),
                'data': result.get('Data'),
                'message': result.get('Message'),
                'requestId': result.get('RequestId')
            })

        except Exception as api_error:
            print(f'\n=== API 错误 ===\n{str(api_error)}')
            # 尝试北京区域
            try:
                config = Config(
                    access_key_id='LTAI5tE8nZL7b1MY1gA18gEX',
                    access_key_secret='sgFOXlzBZUneuphTFVDAYM5qzmo7KV',
                    region_id='cn-beijing',
                    endpoint='green-cip.cn-beijing.aliyuncs.com'
                )
                client = Client(config)
                response = client.image_moderation_with_options(image_moderation_request, runtime)
                result = response.body.to_map()
                
                return jsonify({
                    'code': result.get('Code'),
                    'data': result.get('Data'),
                    'message': result.get('Message'),
                    'requestId': result.get('RequestId')
                })
            except Exception as beijing_error:
                print('Beijing API Error:', str(beijing_error))
                return jsonify({'error': f'API调用错误: {str(beijing_error)}'}), 500

    except Exception as e:
        print(f'\n=== 一般错误 ===\n{str(e)}')
        return jsonify({'error': str(e)}), 500

@app.route('/api/analyze-video', methods=['POST'])
def analyze_video():
    try:
        if 'video' not in request.files:
            return jsonify({'code': 400, 'error': '未找到视频文件'}), 400
            
        video_file = request.files['video']
        service_type = request.form.get('serviceType', 'videoDetection')

        try:
            # 创建客户端
            client = create_client()
            
            # 获取上传凭证
            token_response = client.describe_upload_token()
            upload_token = token_response.body.data

            # 直接读取文件内容到内存
            file_content = video_file.read()

            # 上传文件到OSS（内存直传）
            auth = oss2.StsAuth(
                upload_token.access_key_id,
                upload_token.access_key_secret,
                upload_token.security_token
            )
            bucket = oss2.Bucket(
                auth,
                upload_token.oss_internet_end_point,
                upload_token.bucket_name
            )
            object_name = f"{upload_token.file_name_prefix}{uuid.uuid4()}{os.path.splitext(video_file.filename)[1]}"
            bucket.put_object(object_name, file_content)

            # 提交检测任务
            service_parameters = {
                "ossBucketName": upload_token.bucket_name,
                "ossObjectName": object_name,
                "dataId": str(uuid.uuid4())
            }
            moderation_request = models.VideoModerationRequest(
                service=service_type,
                service_parameters=json.dumps(service_parameters)
            )
            
            # 获取任务ID
            submit_response = client.video_moderation_with_options(moderation_request, util_models.RuntimeOptions())
            task_id = submit_response.body.data.task_id

            # 轮询获取结果
            for i in range(30):
                time.sleep(2)
                result_request = models.VideoModerationResultRequest(
                    service=service_type,
                    service_parameters=json.dumps({'taskId': task_id})
                )
                result_response = client.video_moderation_result(result_request)
                
                if result_response.body.code == 200:
                    result_data = result_response.body.data.to_map()
                    print("视频检测结果:", json.dumps(result_data, indent=2, ensure_ascii=False))
                    
                    if result_data.get('AudioResult') and result_data.get('FrameResult'):
                        response_data = {
                            'code': 200,
                            'data': result_data
                        }
                        print("\n=== 返回给前端的数据 ===")
                        print(json.dumps(response_data, indent=2, ensure_ascii=False))
                        return jsonify(response_data)
                    elif result_data.get('Status') == 'running':
                        continue
                    else:
                        return jsonify({'code': 500, 'error': '分析失败'}), 500

            return jsonify({'code': 500, 'error': '检测超时'}), 500

        except Exception as e:
            print(f"视频检测异常: {str(e)}")
            return jsonify({'code': 500, 'error': str(e)}), 500

    except Exception as e:
        print(f"外层异常: {str(e)}")
        return jsonify({'code': 500, 'error': str(e)}), 500

if __name__ == '__main__':
    app.run(debug=True, port=5000) 